package com.donsee.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.Random;

public class HexUtil {

    private static final char[] bcdLookup = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    public static final String bytesToHex(byte[] bcd) {
        if (bcd == null) {
            return "";
        }
        StringBuffer s = new StringBuffer(bcd.length * 2);

        for (int i = 0; i < bcd.length; i++) {
            s.append(bcdLookup[(bcd[i] >>> 4) & 0x0f]);
            s.append(bcdLookup[bcd[i] & 0x0f]);
        }

        return s.toString().toUpperCase();
    }

    public static final String bytesToHex(byte[] bcd,int leng) {
        if (bcd == null) {
            return "";
        }
        StringBuffer s = new StringBuffer(bcd.length * 2);

        for (int i = 0; i < leng; i++) {
            s.append(bcdLookup[(bcd[i] >>> 4) & 0x0f]);
            s.append(bcdLookup[bcd[i] & 0x0f]);
        }

        return s.toString().toUpperCase();
    }


    public static final byte[] hexToBytes(String s) {
        byte[] bytes;
        if (s == null || s.length() == 0) {
            return null;
        }

        s = s.replaceAll(" ","");

        bytes = new byte[s.length() / 2];

        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) Integer.parseInt(s.substring(2 * i, 2 * i + 2), 16);
        }

        return bytes;
    }

    public static final int fillHexToBytes(String s, byte[] bytes, int pos){
        if (s == null || s.length() == 0) {
            return 0;
        }
        if (bytes == null || bytes.length == 0) {
            return 0;
        }

        s = s.replaceAll(" ","");

        if((bytes.length - pos) < (s.length() / 2)){
            return 0;
        }

        for (int i = 0; i < s.length() / 2; i++) {
            bytes[pos + i] = (byte) Integer.parseInt(s.substring(2 * i, 2 * i + 2), 16);
        }

        return s.length() / 2;
    }

    public static final int fillHexToBytes(String s, byte[] bytes){
        return fillHexToBytes(s,bytes,0);
    }

    public static byte[] join(byte[]... params) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] res = null;
        try {
            for (int i = 0; i < params.length; i++) {
                baos.write(params[i]);
            }
            res = baos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }


    public static String random(int size) {
        byte[] random = new byte[size];
        Random r = new SecureRandom();
        r.nextBytes(random);
        return bytesToHex(random);
    }

    public static byte[] randomByte(int size) {
        byte[] random = new byte[size];
        Random r = new SecureRandom();
        r.nextBytes(random);
        return random;
    }
}
